package sword.T53;

/**
 * @Author: 18362
 * @Create: 2022-04-09 23:56:01 星期六
 */
class Solution {
    public int search(int[] nums, int target) {
        if (nums.length == 0)
            return 0;
        int lower = lowerBound(nums, target);
        if (nums[lower] != target)
            return 0;
        int upper = upperBound(nums, target);
        return upper - lower;
    }

    private int lowerBound(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target)
                right = mid;
            else
                left = mid + 1;
        }
        return left;
    }

    private int upperBound(int[] nums, int target) {
        int left = 0, right = nums.length;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target)
                left = mid + 1;
            else
                right = mid;
        }
        return left;
    }
}